/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.openjawtech.xscraper.scraper.util;

import org.w3c.dom.Document;
import java.io.InputStream;
import org.cyberneko.html.parsers.DOMParser;
import org.apache.xerces.xni.parser.XMLInputSource;
import com.openjawtech.xscraper.scraper.exception.ScrapeException;
import java.io.File;
import java.io.FileInputStream;

/**
 *
 * @Created on 17-Apr-2009, 19:51:50
 * @author Wenbo.Sun
 */
public class HtmlParserUtil {

    public static Document parse(InputStream is) throws ScrapeException {
        Document doc = null;
        try {
            DOMParser parser = new DOMParser();
            parser.setFeature("http://xml.org/sax/features/namespaces", false);
            XMLInputSource source = new XMLInputSource(null, null, null, is, null);
            parser.parse(source);
            doc = parser.getDocument();
        } catch (Throwable t) {
            throw new ScrapeException("parse html file failed", t);
        }
        return doc;
    }

    public static Document parse(File htmlFile) throws ScrapeException {
        Document doc = null;
        try {
            FileInputStream fis = new FileInputStream(htmlFile);
            doc = parse(fis);
        } catch (Throwable t) {
            throw new ScrapeException("parse html file failed", t);
        }
        return doc;
    }

    public static Document parse(String source) throws ScrapeException {
        Document doc = null;
        try {
            DOMParser parser = new DOMParser();
            parser.setFeature("http://xml.org/sax/features/namespaces", false);
            parser.parse(source);
            doc = parser.getDocument();
        } catch (Throwable t) {
            throw new ScrapeException("parse html file failed", t);
        }
        return doc;
    }
}
